package com.zhupf.hash;

import java.util.HashMap;
import java.util.Map;

/**
 * @author zhupf
 * @date 2023年10月24日 9:17
 * @Description
 */
public class Train1 {

    public static void main(String[] args) {
        int[] nums = {1, 2, 3, 4, 5, 6};
        int target = 11;
        int[] ints = numSum2(nums, target);
        for (int anInt : ints) {
            System.out.println(anInt);
        }

    }

    public static int[] numSum(int[] nums, int target) {
        int[] result = new int[2];
        for (int i = 0; i < nums.length - 1; i++) {
            for (int j = i + 1; j < nums.length; j++) {
                if (nums[i] + nums[j] == target) {
                    result[0] = i;
                    result[1] = j;
                    return result;
                }
            }
        }
        return result;
    }

    /**
     * 使用map解题
     *
     * @param nums
     * @param target
     * @return
     */
    public static int[] numSum2(int[] nums, int target) {
        int[] result = new int[2];
        Map<Integer, Integer> map = new HashMap<>();
        for (int i = 0; i < nums.length; i++) {
            if (map.containsKey(nums[i])) {
                result[0] = i;
                result[1] = map.get(nums[i]);
                return result;
            }
            map.put(target - nums[i], i);
        }
        return result;
    }

}
